package cc.stonemarket.caricature.biz;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import cc.stonemarket.caricature.dao.BookDaoImpl;
import cc.stonemarket.caricature.util.Constants;

/**
 * Android DataManager to encapsulate SQL and DB details. Includes
 * SQLiteOpenHelper, and uses DAO objects (in specified order) to create/update
 * and clear tables, and manipulate data.
 */
public class DBManager {
	
	//TODO ①本类所有用到的DAO
	private BookDaoImpl bookDao;
	
	//写日志用
	public static final String TAG = "DBManager";
	/**整个应用程序所有DAO共用的、单例的、唯一的操作数据库的SQLiteDatabase对象*/
	private SQLiteDatabase globalDB;
	
	/**获得所有DAO共用的SQLiteDatabase对象*/
	public SQLiteDatabase getGlobalDB() {
		this.openDB();
		return this.globalDB;
	}
	
	/**只在Application的子类GlobalVar.java中实例化*/
	public DBManager(final Context context) {
		OpenHelper openHelper = new OpenHelper(context);
		this.globalDB = openHelper.getWritableDatabase();
		this.initDao(globalDB);
		if (openHelper.isDbCreated()) {
			//第一次建表后，插入一些默认的数据到表里。
		}
	}
	
	/**实例化本类所有用到的DAO*/
	private void initDao(SQLiteDatabase globalDB) {
		//TODO ②并注入SQLiteDatabase实例===>globalDB
		bookDao = new BookDaoImpl(globalDB);
		//otherDao = new OtherDaoImpl(globalDB);
		
	}
	
	/**把所有表删除后再重建*/
	public void resetDB() {
		Log.i(TAG,"DBManager Reset DB !!!");
		this.openDB();
		globalDB.beginTransaction();
		try {
			//TODO ③各个DAO的删除、建表操作
			bookDao.resetTable();
			
			globalDB.setTransactionSuccessful();
		} finally {
			globalDB.endTransaction();
		}
		globalDB.execSQL("vacuum");
		//上面一行具体功能请到：http://edu.codepub.com/2009/0814/13520.php看或百度 SQLite vacuum
	}
	
	/**每次使用globalDB时，先调用此方法，确保globalDB的可用性*/
	private void openDB() {
		//globalDB被回收了或关闭了
		if ( this.globalDB==null || !this.globalDB.isOpen() ) {
			try{
				this.globalDB = SQLiteDatabase.openDatabase(Constants.DB_PATH, null,SQLiteDatabase.OPEN_READWRITE);
				this.initDao(this.globalDB);//重新注入
			}catch(Exception E){
				//the database cannot be opened
				Log.e(TAG, "the database cannot be opened---数据库不能打开！！！", E);
			}
		}
	}
	
	/**关闭数据库连接，只在Application子类GlobalVar的onTerminate()方法使用*/
	public void closeDB() {
		if (this.globalDB!=null && this.globalDB.isOpen()) {
			globalDB.close();
		}
	}
	
	/**
	 * 计数查询结果总条数
	 * @param tableName 表名
	 * @param whereClause 查询条件：whereClause="where bookTable.rat = 5"
	 * @return 记录数
	 */
	// protected scope to allow method to be exposed for automated testing 
	protected int getCount(final String tableName, final String whereClause) {
		int result = 0;
		Cursor cursor = this.getGlobalDB().rawQuery("SELECT COUNT(*) FROM " + tableName + " "+ whereClause, null);
		if (cursor.moveToFirst()) {
			result = cursor.getInt(0);
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return result;
	}
	
//=========================================================================================================
	/** 
	 * 【OpenHelper内部类】只是用来建数据库或建表用到。
	 * */
	private static class OpenHelper extends SQLiteOpenHelper {
		/**数据库是否是新建好的*/
		private boolean dbCreated;
		
		public boolean isDbCreated() {
			return dbCreated;
		}
		
		OpenHelper(final Context context) {
			super(context, Constants.DB_NAME, null, Constants.DB_VERSION);
			//当数据库不存在时，就会自动调用onCreate方法，建立新的数据库
			//当数据库有的版本有更新时，就会调用onUpgrade方法
		}
		
		public void onCreate(final SQLiteDatabase openHelperDB) {
			//TODO 调用所有DAO的onCreate静态方法进行建表操作
			BookDaoImpl.onCreate(openHelperDB);
			//OtherDAO.onCreate(openHelperDB);
			dbCreated = true;
		}
		
		public void onUpgrade(final SQLiteDatabase openHelperDB, final int oldVersion, final int newVersion) {
			Log.i(DBManager.TAG, "DBManager's OpenHelper onUpgrade - oldVersion:" + oldVersion + " newVersion:" + newVersion);
			//TODO 调用所有DAO的onUpgrade静态方法进行【删除-建表】操作
			BookDaoImpl.onUpgrade(openHelperDB, oldVersion, newVersion);
			//OtherDAO.onUpgrade(openHelperDB, oldVersion, newVersion);
		}
		
	}
	
	
}





